//
//  userInfo.swift
//  我的微博
//
//  Created by shmily on 15/7/29.
//  Copyright © 2015年 Stanford-IOS8-Swift-shmilyAshen. All rights reserved.
//

import UIKit
/// 授权模型
class UserInfo: NSObject,NSCoding {

    //MARK: - 模型属性
    ///用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    ///access_token的生命周期，单位是秒数。
    var expires_in: NSTimeInterval = 0{
        didSet {
            //当前距离 x 秒后的日期
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    ///生命周期距离当前时间
    var expires_date: NSDate?
    ///当前授权用户的UID。
    var uid: String?
    ///用户头像地址（大图），180×180像素
    var avatar_large: String?
    //友好显示名称
    var name: String?
    
    ///是否登陆成功
    class var isLogon: Bool{
       return UserInfo.getUserInfo() != nil
    }
    
    // MARK: - 静态方法获取用户信息
    ///用户信息单例,不允许外部访问,只能通过UserInfo.getUserInfo()方法访问
    private static var userInfo : UserInfo?
    //获取 保存用户信息的静态属性userInfo
    class func getUserInfo() -> UserInfo? {
        //(1)解档 (如果 userInfo 为 nil, 解档,结果可能为 nil)
        if userInfo == nil {
            userInfo = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserInfo
        }
        //(2)判断时间是否正确
        if let date = userInfo?.expires_date where date.compare(NSDate()) == NSComparisonResult.OrderedAscending {
           return nil
        }
        //返回结果可能为 nil(1或2造成),或者为userInfo
        return userInfo
    }
    
     //MARK: - GET获取name 和 avatar_large ,并且归档
    func loadUserInfo(finished: (error : NSError?) -> ()) {
        if  UserInfo.getUserInfo() == nil {
            return
        }
        //获取 name 和 avatar_large
        NetworkingTools.sharedNetTool.loadUserInfo(uid!) { (result, error) -> () in
            if error != nil {
                finished(error: error)
                return
            }
            
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            //归档入文件
            self.writeToFile()
            //回调
            finished(error: nil)
        }
    }
    
    
    //kvc 初始化类
     init(dict:[String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
        ///一定要设置该值,否则静态变量一直为 nil
        UserInfo.userInfo = self
    }
    
    // MARK: - 归档 & 解档
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in") as NSTimeInterval
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    ///将信息归档到 plist 文件中
    func writeToFile() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserInfo.accountPath)
    }
    
    // MARK: - 其它
    ///沙盒路径
    static let accountPath = NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("accountPath.plist")
    
    
    //防止因为多余的键值对而报错
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    /// 对象描述信息
    override var description: String {
        let properties = ["access_token", "expires_in", "uid","name","avatar_large"]
        
        return "\(dictionaryWithValuesForKeys(properties))"
    }
    
}
